<template>
    <div>
        <div class="userManager">
            <div class="queryForm">
                <query-form
                    :form="searchForm"
                    v-model="userSearch"
                    @searchHandler="searchHandler"
                    @cancelHandler="cancelHandler"
                ></query-form>
            </div>
            <div class="baseTable">
                <div class="action">
                    <el-button type="primary" @click="userCreate" v-has="'user-create'">
                        新增
                    </el-button>
                    <el-button type="danger" @click="clearList" v-has="'user-patch-delete'">
                        批量删除
                    </el-button>
                </div>
                <el-table ref="listRef" :data="userList" style="width: 100%">
                    <el-table-column type="selection" width="55" />
                    <el-table-column
                        v-for="ele in columns"
                        :key="ele.prop"
                        :prop="ele.prop"
                        :label="ele.label"
                        :formatter="ele.formatter"
                        :width="ele.width"
                    />
                    <el-table-column property="address" label="操作" min-width="120">
                        <template #default="scope">
                            <el-button type="primary" @click="edit(scope.row)" v-has="'user-edit'">
                                编辑
                            </el-button>
                            <el-button
                                type="danger"
                                @click="deleteItem(scope.row)"
                                v-has="'user-delete'"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pages">
                    <el-pagination
                        :current-page="thispage"
                        background
                        layout="prev, pager, next"
                        :total="totalPage"
                        @current-change="pageChange"
                    />
                </div>
            </div>
        </div>
        <el-dialog v-model="showDialog" @close="close">
            <el-form :model="form" ref="dialogForm" :rules="rules">
                <el-form-item label="用户名" prop="userName" label-width="100">
                    <el-input v-model="form.userName" autocomplete="off" />
                </el-form-item>
                <el-form-item label="用户邮箱" prop="userEmail" label-width="100">
                    <el-input v-model="form.userEmail" autocomplete="off" />
                </el-form-item>
                <el-form-item label="号码" prop="mobile" label-width="100">
                    <el-input v-model="form.mobile" autocomplete="off" />
                </el-form-item>
                <el-form-item label="岗位" prop="job" label-width="100">
                    <el-input v-model="form.job" autocomplete="off" />
                </el-form-item>
                <el-form-item label="状态" prop="state" label-width="100">
                    <el-select v-model="form.state" placeholder="用户角色">
                        <el-option label="在职" :value="1" />
                        <el-option label="离职" :value="2" />
                        <el-option label="试用期" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item label="系统角色" prop="role" label-width="100">
                    <el-select
                        v-model="form.roleList"
                        multiple
                        placeholder="选择用户角色"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in roleList"
                            :key="item._id"
                            :label="item.roleName"
                            :value="item._id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-cascader
                    v-model="form.deptId"
                    :options="deptList"
                    :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
                    clearable
                    placeholder="请选择你的部门"
                />
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="submit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import api from '../api';
import { ref, reactive, nextTick, toRaw, getCurrentInstance } from 'vue';
import utils from './../utils/index';
const totalPage = ref(null);
const columns = reactive([
    {
        label: '用户Id',
        prop: 'userId',
        width: '120',
    },
    {
        label: '用户名',
        prop: 'userName',
        width: '100',
    },
    {
        label: '用户邮箱',
        prop: 'userEmail',
        width: '180',
    },
    {
        label: '用户角色',
        prop: 'role',
        formatter(row, column, value) {
            return {
                0: '管理员',
                1: '普通用户',
            }[value];
        },
        width: '120',
    },
    {
        label: '用户状态',
        prop: 'state',
        formatter(row, column, value) {
            return {
                1: '在职',
                2: '离职',
                3: '试用期',
            }[value];
        },
        width: '120',
    },
    {
        label: '注册时间',
        prop: 'createTime',
        formatter(row, column, value) {
            return utils.formateDate(new Date(value));
        },
        width: '210',
    },
    {
        label: '最后登录时间',
        prop: 'lastLoginTime',
        formatter(row, column, value) {
            return utils.formateDate(new Date(value));
        },
        width: '210',
    },
]);
const user = reactive({
    state: 0,
});
const pager = reactive({
    pageNum: 1,
    pageSize: 10,
});
const userList = ref([]);
const showDialog = ref(false);
const dialogForm = ref(null);
const listRef = ref(null);
const userSearch = ref({
    userId: '',
    userName: '',
    state: 0,
});
let target = {};
const rules = reactive({
    userName: {
        required: true,
        message: '请输入用户名',
        trigger: 'blur',
    },
    userEmail: {
        required: true,
        message: '请输入邮箱',
        trigger: 'blur',
    },
    mobile: [
        {
            pattern: /1[3-9]\d{9}/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
        },
    ],
});
let actions = ref(null);
// 新增框默认状态
let form = reactive({
    state: '3',
});
const roleList = ref([]);
const deptList = ref([]);
const thispage = ref(null);

/********************/
const getUserList = async () => {
    let params = { ...user, ...pager };
    let { list, page } = await api.getUserList(params);
    totalPage.value = page.total;
    userList.value = list;
};

const getAllRoleList = async () => {
    roleList.value = await api.getAllRoleList();
};

const getDeptList = async () => {
    deptList.value = await api.getDeptList();
};

const deleteUser = async idArray => {
    let data = { userIds: idArray };
    await api.deleteUser(data);
};

// 重置表单
const resetForm = () => {
    dialogForm.value.resetFields();
};
/*******
 * **********
 * *********/
const cancel = () => {
    resetForm();
    showDialog.value = !showDialog.value;
};
const close = () => {
    resetForm();
};
const userCreate = () => {
    actions.value = 'add';
    showDialog.value = !showDialog.value;
};
const submit = () => {
    dialogForm.value.validate(async vaild => {
        if (vaild) {
            let data = toRaw(form);
            data.action = actions.value;
            console.log(data);
            let res = await api.userOperate(data);
            getUserList();
            showDialog.value = !showDialog.value;
            resetForm();
        }
    });
};

const edit = row => {
    actions.value = 'edit';
    showDialog.value = true;
    nextTick(() => {
        Object.assign(form, row);
    });
};

const deleteItem = row => {
    let userIds = [];
    userIds.push(row.userId);
    deleteUser(userIds);
    user.state = 1;
    getUserList();
};

const clearList = async () => {
    let list = listRef.value.getSelectionRows();
    let userIds = [];
    list.forEach(item => {
        userIds.push(item.userId);
    });
    deleteUser(userIds);
    user.state = 1;
    getUserList();
};
const searchHandler = async userSearch => {
    target = userSearch.value;
    let params = { ...pager, ...target };
    console.log(params);
    let { list, page } = await api.getUserList(params);
    totalPage.value = page.total;
    userList.value = list;
};
const cancelHandler = () => {
    getUserList();
};
const pageChange = async pages => {
    pager.pageNum = pages;
    let params = { ...pager, ...target };
    let { list, page } = await api.getUserList(params);
    totalPage.value = page.total;
    userList.value = list;
};

//定义searchForm
const searchForm = [
    {
        type: 'input',
        label: '用户Id',
        prop: 'userId',
        placeholder: '请输入用户Id',
    },
    {
        type: 'input',
        label: '用户名称',
        prop: 'userName',
        placeholder: '请输入用户名称',
    },
    {
        type: 'select',
        label: '状态',
        prop: 'state',
        placeholder: '请选择状态',
        option: [
            {
                value: 0,
                label: '所有',
            },
            {
                value: 1,
                label: '在职',
            },
            {
                value: 2,
                label: '离职',
            },
            {
                value: 3,
                label: '试用期',
            },
        ],
    },
];

getUserList();
getAllRoleList();
getDeptList();
</script>

<style lang="scss" scoped>
.userManager {
    .queryForm {
        width: 100%;
        // height: 65px;
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;
        display: flex;
        align-items: center;
        padding-top: 20px;
        padding-left: 40px;
    }
    .baseTable {
        margin-top: 20px;
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;
        .action {
            width: 100%;
            height: 55px;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #f1f1f1;
            button {
                margin-left: 20px;
                font-weight: bold;
            }
        }
        .pages {
            margin-top: 20px;
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
}
</style>
